#include <fstream>
#include <string>
#include <fcntl.h>
#include <stdio.h>
#include "util.h" 

using namespace std;
typedef unsigned long long uint64;


// a simple write benchmark

void WriteBuffered(string fn, uint64 size ) {
  FILE *f = fopen(fn.c_str(), "w");
  uint64 wsize = size / sizeof(uint64);
  uint64 * a = new uint64[wsize];
  for (uint64 i=0; i<wsize; i++) a[i] = i;
  uint64 t0 = TimeNS();
  cout << "ready to write" << endl;
  fwrite(a, wsize, sizeof(uint64), f);
  fflush(f);
  fclose(f);  
  uint64 t1 = TimeNS();
  cout << "finished writing MBPS = " << ((double)size) / (double)(t1-t0) << endl;
}
void WriteUnBuffered(string fn, uint64 size) {
  int fd = open(fn.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0644);
  uint64 wsize = size / sizeof(uint64);
  uint64 * a = new uint64[wsize];
  for (uint64 i=0; i<wsize; i++) a[i] = rand();
  uint64 t0 = TimeNS();
  cout << "ready to write" << endl;
  write(fd, a, size);
  fsync(fd);
  close(fd);  
  uint64 t1 = TimeNS();
  cout << "finished writing MBPS = " << ((double)size) / (double)(t1-t0) << endl;
}

int main(int argc, char ** argv) {
  string opt = argv[1];
  string fn = argv[2];
  uint64 size = 1ull << (atoi(argv[3]));
  
  if (opt == "b") WriteBuffered(fn, size);
  else WriteUnBuffered(fn, size);
  return 0;
}
